package com.sx.mvvmlibs.utils

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


/**
 * @Author: YY
 * @Date: 2022/1/5
 * @Describe: TODO
 */
object Utils {

    fun releaseBinding(startClz: Class<*>?, targetClz: Class<*>?, obj: Any, filed: String) {
        // 通过反射，解决内存泄露问题
        CoroutineScope(Dispatchers.Main).launch {
            var clz = startClz
            while (clz != null) {
                // 找到 mBinding 所在的类
                if (clz == targetClz) {
                    try {
                        val field = clz.getDeclaredField(filed)
                        field.isAccessible = true
                        field.set(obj, null)
                    } catch (ignore: Exception) {
                    }
                }
                clz = clz.superclass
            }
        }
    }
}